package com.zh.note.huawei.twohundred.求最大数字;

import java.util.*;

public class Main {
    static List<Integer> resList = new ArrayList<>();
    static List<String> inputStrs = new ArrayList<>();

    // 判断子序列
    public static boolean isSubSequence(List<String> child) {
        int index = 0;
        int count = 0;
        for (int i = 0; i < child.size(); i++) {
            String str = child.get(i);
            for (int j = index; j < inputStrs.size(); j++) {
                String temp = inputStrs.get(j);
                if (temp.equals(str)) {
                    index = j + 1;
                    count++;
                    break;
                }
                if (j == inputStrs.size() - 1) {
                    return false;
                }
            }
        }
        return count == child.size();
    }

    public static boolean isSubSequence2(List<String> child) {
        int i = 0;
        int j = 0;
        while (i < child.size() && j < inputStrs.size()) {
            if (child.get(i).equals(inputStrs.get(j))) {
                i++;
            }
            j++;
        }
        return i == child.size();
    }

    public static void dfs(List<String> strs, int start, int end) {
        if (start == end) {
            String numStr = String.join("", strs);
            if (!resList.contains(Integer.parseInt(numStr)) && isSubSequence2(strs)) {
                resList.add(Integer.parseInt(numStr));
            }
        } else {
            for (int i = start; i < strs.size(); i++) {
                if (i != start && strs.get(i).equals(strs.get(start))) {
                    continue;
                }
                Collections.swap(strs, i, start);
                if (strs.get(0).equals("0")) {
                    continue;
                }
                dfs(strs, start + 1, end);
                Collections.swap(strs, i, start);
            }
        }
    }

    public static void main(String[] args) {
        // Scanner sc = new Scanner(System.in);
        // String inputStrsStr = sc.nextLine();
        String inputStrsStr = "5445795045";
        for (int i = 0; i < inputStrsStr.length(); i++) {
            String inputStr = String.valueOf(inputStrsStr.charAt(i));
            inputStrs.add(inputStr);
        }
        // 统计每个元素出现次数
        Map<String, Integer> map = new HashMap<>();
        for (String inputStr : inputStrs) {
            map.put(inputStr, map.getOrDefault(inputStr, 0) + 1);
        }
        List<String> lis = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            String num = entry.getKey();
            lis.add(num);
            if (entry.getValue() >= 2) {
                lis.add(num);
            }
        }
        dfs(lis, 0, lis.size() - 1);
        Collections.sort(resList);
        System.out.println(resList.get(resList.size() - 1));
    }
}
